package org.netty.client.config;

import java.net.InetSocketAddress;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

@Component("clientServer")
public class NettyClient {

	private Logger logger = LoggerFactory.getLogger(NettyClient.class);
	
	EventLoopGroup workerGroup = new NioEventLoopGroup();
	
	private Channel channel;
	
	public ChannelFuture bing(InetSocketAddress address) {
        ChannelFuture channelFuture = null;
        try {
        	Bootstrap b = new Bootstrap();
        	b.group(workerGroup);
            b.channel(NioSocketChannel.class);
            b.option(ChannelOption.AUTO_READ, true);
            b.handler(new CustomizeChannelInit());
            
            channelFuture = b.connect(address).sync();
            logger.info("netty client start done.");

            //向服务端发送信息
            channelFuture.channel().writeAndFlush("你好，SpringBoot启动的netty服务端，'我的结尾是一个换行符，用于传输半包粘包处理'\r\n");

            channel = channelFuture.channel();
        } catch (Exception e) {
            logger.error(e.getMessage());
        } finally {
            if (null != channelFuture && channelFuture.isSuccess()) {
                logger.info("netty client start done. ");
            } else {
                logger.error("netty client start error. ");
            }
        }
        return channelFuture;
    }

    public void destroy() {
        if (null == channel) return;
        channel.close();
        workerGroup.shutdownGracefully();
    }

    public Channel getChannel() {
        return channel;
    }
}
